<?php
namespace Api\Openapi;

use Core\Env;
use S\Http;
use S\Config;

/**
 * Class File
 * @package Api\Openapi
 * @description 文件sdk
 */
class File extends Util {

    const URI_DOWNLOAD = "file/download";
    const URI_UPLOAD = "file/upload";
    const DEFAULT_FILENAME_TYPE = 0;

    /**
     * 文件下载
     * @param string $name 文件标志
     *
     * @return mixed
     * @throws Exception
     */
    public static function download($name) {
        return self::downloadWithCategoryDate($name, null, null);
    }

    /**
     * 下载指定分类、日期的文件
     *
     * @param $name
     * @param $category
     * @param $date
     *
     * @return mixed
     */
    public static function downloadWithCategoryDate($name, $category, $date) {
        $timestamp = time();
        $arr_sign = array('name' => $name);
        $get_params = array(
            "appkey" => Config::confSecurity("openapi.app_key"),
            "t"      => $timestamp,
            'name'   => $name,
        );
        if (isset($category) && isset($date)) {
            $arr_sign['category'] = $get_params['category'] = $category;
            $arr_sign['date'] = $get_params['date'] = $date;
        }
        $get_params['m'] = self::getSign($timestamp, $arr_sign);

        $url = (Env::isProductEnv() ? self::PRD_URL : self::TEST_URL);
        $http = new Http($url);
        try {
            $response = $http->request('GET', self::URI_DOWNLOAD, $get_params);
        } catch (\Exception $e) {
            self::$_err_msg = $e->getMessage();

            return false;
        }

        $ret = json_decode($response, true);
        if ($ret) {
            if (isset($ret["retcode"]) && (self::ERR_CODE_SUCCESS != $ret["retcode"])) {
                self::$_err_code = $ret["retcode"];
                self::$_err_msg = $ret["msg"];

                return false;
            }

            return $response;
        } else {
            return (false === $response ? null : $response);
        }

    }

    /**
     * 文件上传
     * @param string $category 目录
     * @param string $file 本地文件绝对路径
     * @param string $filename default null
     * @param int    $timeout
     * @return  string 文件标志  需要使用文件标志来下载文件
     * @throws Exception
     */
    public static function upload($category, $file, $filename = null, $timeout = Http::TIMEOUT) {
        $timestamp = time();
        $file = realpath($file);
        $base = array(
            'category' => $category,
        );
        if (!empty($filename)) {
            $base['filename'] = $filename;
        }
        $get_params = array(
            "appkey"   => Config::confSecurity("openapi.app_key"),
            "t"        => $timestamp,
            "m"        => self::getSign($timestamp, $base),
            'category' => $category,
            'filename' => $filename,
        );
        $get_strs = array();
        foreach ($get_params as $key => $val) {
            $get_strs[] = "{$key}={$val}";
        }

        $baseUrl = (Env::isProductEnv() ? self::PRD_URL : self::TEST_URL);
        $path = self::URI_UPLOAD . "?" . implode("&", $get_strs);
        $http = new Http($baseUrl);
        $response = $http->request('POST', $path, null, array(
            'timeout'   => $timeout,
            'multipart' => array(
                array(
                    'name'     => 'file',
                    'contents' => fopen($file, 'r'),
                    'filename' => $filename,
                ),
            ),
        ));
        if (empty($response)) {
            self::$_err_msg = "empty response from openapi";

            return false;
        }

        $result = json_decode($response, true);
        if (empty($result)) {
            self::$_err_msg = "error format response from openapi";

            return false;
        }
        if (self::ERR_CODE_SUCCESS != $result["retcode"]) {
            self::$_err_code = $result["retcode"];
            self::$_err_msg = $result["msg"];

            return false;
        }

        return $result['name'];
    }

} 
